import axios from "axios";
import cheerio from "cheerio";
import path from 'path'
import apilist from './apilist.json'
import fs from 'fs'
import x2js from 'fast-xml-parser'

//请求交由axios来实现,该js用于请求接口管理,定义不同的配置方便调用.
//dom操作交由cheerio来实现,不再去进行与渲染进程通信.
//实际测试,交给渲染进程可以减少打包大小,但是传输消耗更大.
//electron打包本身就很庞大,所以可以不在乎cheerio的大小,最主要是通信写起来不舒服.
export const youkuvip = function (timeout) {
  return axios
    .get("https://home.vip.youku.com/api/granary/index?pageNo=1&pf=1", {
      headers: {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44",
        Cookie: "cna=IBMhGGWf01ACAbaVvbYLvo5q;",
      },
      timeout,
    })
    .then((response) => {
      if (response.data.code == "200") {
        let arr = response.data.data.modules[0].slides;
        return arr.map((value) => {
          return {
            title: value.title.trim(),
            pic: value.poster,
          };
        });
      } else {
        //所有数据不对的情况或者失败都返回空数组
        //优点:传递时直接判断是否为空数组会很方便做错误处理
        //缺点:无法追踪错误,例如,是网络问题或者其他问题!
        //就类似电脑出问题一律重启一样的解决方案
        return [];
      }
    })
    .catch(() => []);
};

export const iqiyi = function (timeout) {
  return axios
    .get("https://www.iqiyi.com/lib/", {
      timeout,
    })
    .then((response) => {
      if (response.status) {
        let htmlString = response.data;
        let $ = cheerio.load(htmlString);
        let lis = $(".focusSearch_mainList>li").toArray();
        return lis.map((el) => {
          return {
            pic: "https:" + el.attribs.style.match(/\((.*?)\)/)[1],
            title: el.firstChild.next.attribs["data-indexfocus-title"].trim(),
          };
        });
      }
    })
    .catch(() => []);
};

export const videos = function (name, timeout) {
  let prmS = []
  const filepath = path.resolve(__dirname,'./apilist.json')
  let startLen = apilist.length
  apilist.forEach((_api, idx) => {
    let reqUrl = `${_api.url}?ac=list&wd=${encodeURI(name)}`
    prmS.push(axios.get(reqUrl, {
      timeout
    }).then(res => {
      res.apiName = _api.name
      return res
    }).catch(reason => {
      //如果站点失效,删除该条数据
      //此处code可能并不一致,可能需要添加完备
      if (reason.code && reason.code == 'ENOTFOUND') {
        apilist.splice(idx, 1)
      }
    }))
  })

  Promise.allSettled(prmS).then(resList => {
    let endLen = apilist.length
    //删除处理
    if(endLen != startLen){
      fs.writeFile('./apilist.json',JSON.stringify(apilist),(err)=>{
        if(err){
          //TODO写入错误处理
        }
      })
    }
  })
}